package com.dynamic.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.dynamic.entity.Tenant;
import com.dynamic.mapper.TenantMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

@Component
public class DynamicConfig {
    @Resource
    private TenantMapper tenantMapper;
    @Resource
    private DynamicDataSourceProperties dynamicDataSourceProperties;


    @PostConstruct
    public void initDataSource(){
        List<Tenant> tenants = this.tenantMapper.selectAll();
        Map<String, DataSourceProperty> datasource = dynamicDataSourceProperties.getDatasource();
        for (Tenant tenant : tenants) {
            DataSourceProperty dataSourceProperty=new DataSourceProperty();
            dataSourceProperty.setDriverClassName(tenant.getDataSourceDriver());
            dataSourceProperty.setUrl(tenant.getDataSourceUrl());
            dataSourceProperty.setUsername(tenant.getDataSourceUserName());
            dataSourceProperty.setPassword(tenant.getDataSourcePassword());
            datasource.put(tenant.getCode(),dataSourceProperty);
        }
        dynamicDataSourceProperties.setDatasource(datasource);
    }

}
